import React, { useState, useCallback, useEffect } from "react";
import { NextPage } from "next";
import { PageHeader, Input, Button, message, Drawer, Form, Icon } from "antd";

import { Editor as BEditor } from "@/components/Editor";
import style from "./index.module.scss";
import { FileDrawer } from "@/components/FileDrawer";
import { PageApi } from "@/api/page";
const STATUS = {
  DRAFT: "draft",
  PUBLISH: "publish"
};
interface IProps {
  page: IPage;
}
const Editor: NextPage<IProps> = ({ page: defaultPage = {} }) => {
  const [visible, setVisible] = useState(false);
  const [settingVisible, setSettingVisible] = useState(false);
  const [page, setPage] = useState<any>(defaultPage);

  const preview = () => {};
  // 保存为草稿
  const saveDarft = useCallback(() => {
    const { id } = page;
    page.status = STATUS.DRAFT;
    if (!page.name) {
      message.warn("请输入页面标题");
      return;
    }
    if (id) {
      PageApi.updatePage(id, page).then(res => {
        setPage(res);
        message.success("页面已保存为草稿");
      });
    } else {
      PageApi.addPage(page).then(res => {
        setPage(res);
        message.success("页面已保存为草稿");
      });
    }
  }, [page]);
  //发布
  const saveOrPublish = () => {
    const { id } = page;
    page.status = STATUS.PUBLISH;
    const handle = res => {
      message.success("页面已发布");
      setPage(res);
      setSettingVisible(false);
    };
    if (id) {
      PageApi.updatePage(id, page).then(handle);
    } else {
      PageApi.addPage(page).then(handle);
    }
  };
  return (
    <div className={style.wrapper}>
      <PageHeader
        onBack={() => window.close()}
        title={
          <Input
            placeholder="页面名称"
            value={defaultPage?.name}
            onChange={e => {
              page.name = e.target.value;
              setPage(page);
            }}
          />
        }
        extra={[
          <Button
            type="dashed"
            key={3}
            onClick={() => {
              setVisible(true);
            }}
          >
            文件库
          </Button>,
          <Button key={1}>预览</Button>,
          <Button
            key={4}
            onClick={() => {
              let canPublish = true;
              void [
                ["name", "请输入页面名称"],
                ["content", "请输入页面内容"]
              ].forEach(([key, msg]) => {
                if (!page[key]) {
                  message.warn(msg);
                  canPublish = false;
                }
              });
              if (!canPublish) {
                return;
              }
              setSettingVisible(true);
            }}
            type="primary"
          >
            保存
          </Button>
        ]}
      ></PageHeader>
      <div className={style.container}>
        <BEditor
          value={defaultPage?.content}
          onChange={value => {
            page.content = value;
            setPage(page);
            return page;
          }}
        />
      </div>
      <FileDrawer
        visible={visible}
        isCopy={true}
        closeAfterClick={true}
        onChange={url => {
          setPage(page => {
            page.cover = url;
            console.log(page);
            return page;
          });
        }}
        onClose={() => {
          setVisible(false);
        }}
      />
      <Drawer
        placement={"right"}
        width={480}
        title="页面属性"
        visible={settingVisible}
        onClose={() => setSettingVisible(false)}
      >
        <Form.Item>
          <Input
            defaultValue={page?.cover}
            addonAfter={
              <Icon type="file-image" onClick={() => setVisible(true)} />
            }
            onChange={e => {
              const value = e.target.value;
              setPage(page => {
                page.cover = value;
                return page;
              });
            }}
          />
        </Form.Item>
        <Form.Item>
          <Input
            defaultValue={page?.path}
            placeholder="输入页面路径"
            onChange={e => {
              const value = e.target.value;
              setPage(page => {
                page.path = value;
                return page;
              });
            }}
          />
        </Form.Item>
        <Form.Item>
          <Button style={{ marginRight: 15 }} onClick={saveDarft}>
            保存草稿
          </Button>
          <Button type="primary" onClick={saveOrPublish}>
            发布
          </Button>
        </Form.Item>
      </Drawer>
    </div>
  );
};

Editor.getInitialProps = async ctx => {
  const { id } = ctx.query;
  const page = await PageApi.getPage(id);
  return { page };
};

export default Editor;
